package priv.books.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import priv.books.pojo.BooksType;
import priv.books.pojo.ResultMessage;
import priv.books.service.BooksTypeService;

/**
 * 书籍类型控制器
 */
@RestController
@RequestMapping("/booksType")
public class BooksTypeController {

    @Autowired
    private BooksTypeService booksTypeService;

    /**
     * 修改信息
     * @param booksType
     * @return
     */
    @PostMapping("/updateInfo")
    public ResultMessage updateInfo(BooksType booksType) {
        try {
            // 设置修改时间
            booksType.setUpdateDate(DateUtil.now());
            // 调用service 修改方法
            boolean result = booksTypeService.updateById(booksType);
            if(result) {
                return new ResultMessage(0, "操作成功！");
            }
            return new ResultMessage(207, "操作无响应！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(500, "出现异常：" + e.getMessage());
        }
    }

    /**
     * 新增信息
     * @param booksType
     * @return
     */
    @PostMapping("/insertInfo")
    public ResultMessage insertInfo(BooksType booksType) {
        try {
            // 设置修改时间
            booksType.setCreateDate(DateUtil.now());
            booksType.setUpdateDate(DateUtil.now());
            // 调用service 修改方法
            boolean result = booksTypeService.save(booksType);
            if(result) {
                return new ResultMessage(0, "操作成功！");
            }
            return new ResultMessage(207, "操作无响应！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(500, "出现异常：" + e.getMessage());
        }
    }

    /**
     * 删除信息
     * @param id
     * @return
     */
    @DeleteMapping("/deleteInfo")
    public ResultMessage deleteInfo(Integer id, String ids) {
        try {
            // 调用service 修改方法
            Integer result = null;
            if(id != null && id != 0) {
                result = booksTypeService.deleteInfo(id);
            } else if(!StrUtil.isBlankOrUndefined(ids)) {
                result = booksTypeService.deleteInfo(ids);
            }
            if(result > 0) {
                return new ResultMessage(0, "操作成功！");
            } else if(result == -500) {
                return new ResultMessage(207, "该类型下还有绑定书籍信息！不可删除！");
            }
            return new ResultMessage(207, "操作无响应！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(500, "出现异常：" + e.getMessage());
        }
    }

}
